//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.jim.server.util;

import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jim.core.ImChannelContext;
import org.jim.core.ImSessionContext;
import org.jim.core.config.ImConfig.Global;
import org.jim.core.http.HttpConfig;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.User;
import org.jim.core.session.id.impl.UUIDSessionIdGenerator;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;

public class ChatKit {
	private static Logger log = Logger.getLogger(ChatKit.class);

	public ChatKit() {
	}

	public static ChatBody toChatBody(byte[] body, ImChannelContext imChannelContext) {
		ChatBody chatReqBody = parseChatBody(body);
		if (chatReqBody != null && StringUtils.isEmpty(chatReqBody.getFromId())) {
			ImSessionContext imSessionContext = imChannelContext.getSessionContext();
			User user = imSessionContext.getImClientNode().getUser();
			if (user != null) {
				chatReqBody.setFromId(user.getUserId());
			} else {
				chatReqBody.setFromId(imChannelContext.getId());
			}
		}

		return chatReqBody;
	}

	private static ChatBody parseChatBody(byte[] body) {
		if (body == null) {
			return null;
		} else {
			ChatBody chatReqBody = null;

			try {
				String text = new String(body, "utf-8");
				chatReqBody = (ChatBody)JsonKit.toBean(text, ChatBody.class);
				if (chatReqBody != null) {
					if (chatReqBody.getCreateTime() == null) {
						chatReqBody.setCreateTime(System.currentTimeMillis());
					}

					if (StringUtils.isEmpty(chatReqBody.getId())) {
						chatReqBody.setId(UUIDSessionIdGenerator.instance.sessionId((HttpConfig)null));
					}

					return chatReqBody;
				}
			} catch (Exception var3) {
				log.error(var3.toString());
			}

			return chatReqBody;
		}
	}

	public static ChatBody parseChatBody(String bodyStr) {
		if (bodyStr == null) {
			return null;
		} else {
			try {
				return parseChatBody(bodyStr.getBytes("utf-8"));
			} catch (Exception var2) {
				log.error(var2);
				return null;
			}
		}
	}

	public static boolean isOnline(String userId, boolean isStore) {
		if (isStore) {
			ImServerConfig imServerConfig = (ImServerConfig)Global.get();
			return imServerConfig.getMessageHelper().isOnline(userId);
		} else {
			List<ImChannelContext> imChannelContexts = JimServerAPI.getByUserId(userId);
			return CollectionUtils.isNotEmpty(imChannelContexts);
		}
	}

	public static String sessionId(String from, String to) {
		return from.compareTo(to) <= 0 ? from + "-" + to : to + "-" + from;
	}
}
